import React, { useState } from 'react';
import {
  Card,
  Row,
  Col,
  Typography,
  Form,
  Switch,
  Select,
  Button,
  Divider,
  Space,
  Alert,
  Modal,
  message,
  Tabs,
  Input,
  Radio,
  Slider
} from 'antd';
import {
  SettingOutlined,
  UserOutlined,
  BellOutlined,
  SafetyOutlined,
  ExportOutlined,
  ImportOutlined,
  DeleteOutlined,
  SaveOutlined
} from '@ant-design/icons';
import { useAuth } from '../../contexts/AuthProvider';
import './index.less';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface UserSettings {
  theme: 'light' | 'dark' | 'auto';
  language: 'zh-CN' | 'en-US';
  notifications: {
    email: boolean;
    push: boolean;
    sound: boolean;
  };
  privacy: {
    dataCollection: boolean;
    analytics: boolean;
    crashReports: boolean;
  };
  investment: {
    defaultCurrency: string;
    riskLevel: 'conservative' | 'moderate' | 'aggressive';
    autoSave: boolean;
    reminderInterval: number;
  };
}

const Settings: React.FC = () => {
  const { user, profile } = useAuth();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('general');

  // 默认设置
  const [settings, setSettings] = useState<UserSettings>({
    theme: 'light',
    language: 'zh-CN',
    notifications: {
      email: true,
      push: true,
      sound: false
    },
    privacy: {
      dataCollection: false,
      analytics: false,
      crashReports: true
    },
    investment: {
      defaultCurrency: 'CNY',
      riskLevel: 'moderate',
      autoSave: true,
      reminderInterval: 7
    }
  });

  // 保存设置
  const handleSave = async (values: any) => {
    setLoading(true);
    try {
      // 模拟保存到本地存储
      const newSettings = { ...settings, ...values };
      localStorage.setItem('userSettings', JSON.stringify(newSettings));
      setSettings(newSettings);
      message.success('设置保存成功！');
    } catch (error) {
      message.error('保存设置失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 重置设置
  const handleReset = () => {
    Modal.confirm({
      title: '重置设置',
      content: '确定要重置所有设置到默认值吗？此操作不可撤销。',
      onOk: () => {
        localStorage.removeItem('userSettings');
        form.resetFields();
        message.success('设置已重置');
      }
    });
  };

  // 导出设置
  const handleExport = () => {
    const dataStr = JSON.stringify(settings, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'invest-tools-settings.json';
    link.click();
    URL.revokeObjectURL(url);
    message.success('设置已导出');
  };

  // 导入设置
  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const importedSettings = JSON.parse(e.target?.result as string);
            setSettings(importedSettings);
            form.setFieldsValue(importedSettings);
            localStorage.setItem('userSettings', JSON.stringify(importedSettings));
            message.success('设置导入成功');
          } catch (error) {
            message.error('导入失败，文件格式不正确');
          }
        };
        reader.readAsText(file);
      }
    };
    input.click();
  };

  // 清除所有数据
  const handleClearData = () => {
    Modal.confirm({
      title: '清除所有数据',
      content: '确定要清除所有本地数据吗？包括投资记录、计划等。此操作不可撤销！',
      okText: '确认清除',
      okType: 'danger',
      onOk: () => {
        localStorage.clear();
        message.success('所有数据已清除');
      }
    });
  };

  const tabItems = [
    {
      key: 'general',
      label: (
        <span>
          <SettingOutlined />
          常规设置
        </span>
      ),
      children: (
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={12}>
            <Card title="界面设置" size="small">
              <Form.Item label="主题模式" name={['theme']}>
                <Radio.Group>
                  <Radio value="light">浅色模式</Radio>
                  <Radio value="dark">深色模式</Radio>
                  <Radio value="auto">跟随系统</Radio>
                </Radio.Group>
              </Form.Item>
              
              <Form.Item label="语言" name={['language']}>
                <Select>
                  <Option value="zh-CN">简体中文</Option>
                  <Option value="en-US">English</Option>
                </Select>
              </Form.Item>
            </Card>
          </Col>
          
          <Col xs={24} lg={12}>
            <Card title="投资设置" size="small">
              <Form.Item label="默认货币" name={['investment', 'defaultCurrency']}>
                <Select>
                  <Option value="CNY">人民币 (CNY)</Option>
                  <Option value="USD">美元 (USD)</Option>
                  <Option value="HKD">港币 (HKD)</Option>
                </Select>
              </Form.Item>
              
              <Form.Item label="风险偏好" name={['investment', 'riskLevel']}>
                <Radio.Group>
                  <Radio value="conservative">保守型</Radio>
                  <Radio value="moderate">稳健型</Radio>
                  <Radio value="aggressive">激进型</Radio>
                </Radio.Group>
              </Form.Item>
              
              <Form.Item label="自动保存" name={['investment', 'autoSave']} valuePropName="checked">
                <Switch />
              </Form.Item>
              
              <Form.Item label="提醒间隔（天）" name={['investment', 'reminderInterval']}>
                <Slider min={1} max={30} marks={{ 1: '1天', 7: '1周', 30: '1月' }} />
              </Form.Item>
            </Card>
          </Col>
        </Row>
      )
    },
    {
      key: 'notifications',
      label: (
        <span>
          <BellOutlined />
          通知设置
        </span>
      ),
      children: (
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <Card title="通知偏好" size="small">
              <Form.Item label="邮件通知" name={['notifications', 'email']} valuePropName="checked">
                <Switch />
              </Form.Item>
              <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                接收重要的投资提醒和系统通知邮件
              </Paragraph>
              
              <Form.Item label="推送通知" name={['notifications', 'push']} valuePropName="checked">
                <Switch />
              </Form.Item>
              <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                在浏览器中接收实时推送通知
              </Paragraph>
              
              <Form.Item label="声音提醒" name={['notifications', 'sound']} valuePropName="checked">
                <Switch />
              </Form.Item>
              <Paragraph type="secondary">
                通知时播放提示音
              </Paragraph>
            </Card>
          </Col>
        </Row>
      )
    },
    {
      key: 'privacy',
      label: (
        <span>
          <SafetyOutlined />
          隐私安全
        </span>
      ),
      children: (
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <Card title="隐私设置" size="small">
              <Form.Item label="数据收集" name={['privacy', 'dataCollection']} valuePropName="checked">
                <Switch />
              </Form.Item>
              <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                允许收集匿名使用数据以改进产品体验
              </Paragraph>
              
              <Form.Item label="使用分析" name={['privacy', 'analytics']} valuePropName="checked">
                <Switch />
              </Form.Item>
              <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                允许分析使用行为以优化功能
              </Paragraph>
              
              <Form.Item label="崩溃报告" name={['privacy', 'crashReports']} valuePropName="checked">
                <Switch />
              </Form.Item>
              <Paragraph type="secondary">
                自动发送崩溃报告帮助修复问题
              </Paragraph>
            </Card>
          </Col>
        </Row>
      )
    },
    {
      key: 'data',
      label: (
        <span>
          <ExportOutlined />
          数据管理
        </span>
      ),
      children: (
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <Card title="数据操作" size="small">
              <Space direction="vertical" style={{ width: '100%' }} size="large">
                <div>
                  <Title level={5}>导出数据</Title>
                  <Paragraph type="secondary">
                    将您的设置和数据导出为 JSON 文件，可用于备份或迁移到其他设备
                  </Paragraph>
                  <Button icon={<ExportOutlined />} onClick={handleExport}>
                    导出设置
                  </Button>
                </div>
                
                <Divider />
                
                <div>
                  <Title level={5}>导入数据</Title>
                  <Paragraph type="secondary">
                    从之前导出的 JSON 文件中恢复设置和数据
                  </Paragraph>
                  <Button icon={<ImportOutlined />} onClick={handleImport}>
                    导入设置
                  </Button>
                </div>
                
                <Divider />
                
                <div>
                  <Title level={5}>清除数据</Title>
                  <Alert
                    message="危险操作"
                    description="此操作将清除所有本地存储的数据，包括投资记录、计划等，且不可恢复"
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />
                  <Button 
                    danger 
                    icon={<DeleteOutlined />} 
                    onClick={handleClearData}
                  >
                    清除所有数据
                  </Button>
                </div>
              </Space>
            </Card>
          </Col>
        </Row>
      )
    }
  ];

  return (
    <div className="settings-page">
      <div className="settings-header">
        <Title level={2}>
          <SettingOutlined /> 系统设置
        </Title>
        <Paragraph>
          个性化您的投资工具体验，管理数据和隐私设置
        </Paragraph>
      </div>

      <Form
        form={form}
        layout="vertical"
        initialValues={settings}
        onFinish={handleSave}
      >
        <Card>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={tabItems}
          />
          
          <Divider />
          
          <div className="settings-actions">
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                icon={<SaveOutlined />}
              >
                保存设置
              </Button>
              <Button onClick={handleReset}>
                重置默认
              </Button>
            </Space>
          </div>
        </Card>
      </Form>

      {/* 用户信息卡片 */}
      <Card 
        title={
          <span>
            <UserOutlined /> 账户信息
          </span>
        }
        style={{ marginTop: 24 }}
        size="small"
      >
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12}>
            <Text strong>用户邮箱：</Text>
            <Text>{user?.email || '未登录'}</Text>
          </Col>
          <Col xs={24} sm={12}>
            <Text strong>用户角色：</Text>
            <Text>{profile?.role === 'superadmin' ? '超级管理员' : '普通用户'}</Text>
          </Col>
          <Col xs={24} sm={12}>
            <Text strong>注册时间：</Text>
            <Text>{user?.created_at ? new Date(user.created_at).toLocaleDateString() : '未知'}</Text>
          </Col>
          <Col xs={24} sm={12}>
            <Text strong>最后登录：</Text>
            <Text>{user?.last_sign_in_at ? new Date(user.last_sign_in_at).toLocaleDateString() : '未知'}</Text>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default Settings;